package com.ftdigital.primemovers_operators.util.qrcode;

import java.io.IOException;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ftdigital.primemovers_operators.MainActivity;
import com.ftdigital.primemovers_operators.MyApplication;
import com.ftdigital.primemovers_operators.R;
import com.ftdigital.primemovers_operators.adpter.TextListAdpter;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.config.RequestAddr;
import com.ftdigital.primemovers_operators.fragment.InfoEnsureFragment_;
import com.ftdigital.primemovers_operators.model.AddOilInfo;
import com.ftdigital.primemovers_operators.model.BaseModel;
import com.ftdigital.primemovers_operators.util.XTHttp;
import com.ftdigital.primemovers_operators.util.http.AjaxCallBack;
import com.ftdigital.primemovers_operators.util.qrcode.camera.CameraManager;
import com.ftdigital.primemovers_operators.util.qrcode.decoding.CaptureActivityHandler;
import com.ftdigital.primemovers_operators.util.qrcode.decoding.InactivityTimer;
import com.ftdigital.primemovers_operators.util.qrcode.decoding.RGBLuminanceSource;
import com.ftdigital.primemovers_operators.util.qrcode.view.ViewfinderView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
public class MipcaActivityCapture extends Activity implements Callback , View.OnClickListener{

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;


	private static final int REQUEST_CODE = 100;
	private static final int PARSE_BARCODE_SUC = 300;
	private static final int PARSE_BARCODE_FAIL = 303;
	private ProgressDialog mProgress;
	private String photo_path;
	private Bitmap scanBitmap;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qr_main);
		//ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

		((TextView)findViewById(R.id.toptitle_title)).setText(getResources().getString(R.string.title_qrcode));
		findViewById(R.id.back_btn).setOnClickListener(this);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}


	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.back_btn:
				this.finish();
				break;
		}
	}

	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			mProgress.dismiss();
			switch (msg.what) {
				case PARSE_BARCODE_SUC://转换成功
					onResultHandler();
					break;
				case PARSE_BARCODE_FAIL://转换失败
					Toast.makeText(MipcaActivityCapture.this, (String)msg.obj, Toast.LENGTH_LONG).show();
					break;

			}
		}

	};


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			switch(requestCode){
				case REQUEST_CODE:
					//获取选中图片的路径
					Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
					if (cursor.moveToFirst()) {
						photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
					}
					cursor.close();

					mProgress = new ProgressDialog(MipcaActivityCapture.this);
					mProgress.setMessage("正在扫描...");
					mProgress.setCancelable(false);
					mProgress.show();

					new Thread(new Runnable() {
						@Override
						public void run() {
							Result result = scanningImage(photo_path);  //扫描并返回结果
							if (result != null) {
								Message m = mHandler.obtainMessage();//从消息队列中取出一个消息 重复利用 可以直接发送消息
								m.what = PARSE_BARCODE_SUC;
								m.obj = result.getText();
								mHandler.sendMessage(m);
							} else {
								Message m = mHandler.obtainMessage();
								m.what = PARSE_BARCODE_FAIL;
								m.obj = "Scan failed!";
								mHandler.sendMessage(m);
							}
						}
					}).start();

					break;

			}
		}
	}

	/**
	 * 扫描二维码图片的方法
	 * @param path
	 * @return
	 */
	public Result scanningImage(String path) {
		if(TextUtils.isEmpty(path)){
			return null;
		}
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 先获取原大小
		scanBitmap = BitmapFactory.decodeFile(path, options);//将文件转化为bigmap
		options.inJustDecodeBounds = false; // 获取新的大小
		int sampleSize = (int) (options.outHeight / (float) 200);
		if (sampleSize <= 0)
			sampleSize = 1;
		options.inSampleSize = sampleSize;
		scanBitmap = BitmapFactory.decodeFile(path, options);
		RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		try {
			return reader.decode(bitmap1, hints);

		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (ChecksumException e) {
			e.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * 处理扫描结果
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();
		Toast.makeText(this, resultString, Toast.LENGTH_SHORT).show();
		loadData(resultString);
	}

	private void loadData(String resultString) {
		try {
			requestParams = "car_num=" + resultString
					+ "&gasstation_id=" + MyApplication.userInfo.getData().getGasstation_id()
					+ "&supplier_id=" + MyApplication.userInfo.getData().getSupplier_id();
			requestUrl = RequestAddr.addoilInfo + requestParams;
		} catch (Exception e) {
			e.printStackTrace();
		}
		xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
			@Override
			public void onSuccess(Object object) {
				super.onSuccess(object);
				dealData(object);
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
			}
		});
	}

	AddOilInfo addOilInfo;
	Gson gson = new Gson();
	XTHttp xtHttp = new XTHttp();
	BaseModel baseModel;

	protected String requestUrl = "";//访问地址
	protected String requestParams = "";//访问参数


	private void dealData(Object object) {
		try {
			addOilInfo = gson.fromJson(object.toString(), AddOilInfo.class);
		} catch (JsonSyntaxException e) {
			Toast.makeText(this, R.string.info_empty, Toast.LENGTH_SHORT).show();
			return;
		}

		if (addOilInfo.getData().getList().size() == 0) {
			showInfo("车牌号不正确，请重新确认");
			return;
		} else {
//			MainActivity.getInstance().switchFragment(this, InfoEnsureFragment_.builder()
//					.addOilInfo(addOilInfo)
//					.build());
			onResultHandler();
		}
	}

	AlertDialog infoDialog;

	private void showInfo(String infoContentStr) {
		infoDialog = new AlertDialog.Builder(this).create();
		infoDialog.show();
		Window window = infoDialog.getWindow();
		window.setContentView(R.layout.noticy_sure_dialog);
		window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		TextView sureInfo = (TextView) window.findViewById(R.id.sureinfo);
		TextView infoContent = (TextView) window.findViewById(R.id.info_content);
		sureInfo.setText("确定");
		infoContent.setText(infoContentStr);
		sureInfo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				infoDialog.dismiss();
			}
		});
	}

	/**
	 * 跳转到上一个页面
	 */
	private void onResultHandler(){
//		if(TextUtils.isEmpty(resultString)){
//			Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();
//			return;
//		}
		Intent resultIntent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("addOilInfo", (Serializable) addOilInfo);
		resultIntent.putExtras(bundle);
		this.setResult(RESULT_OK, resultIntent);
		this.finish();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
							   int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};


}